'use strict';

const Controller = require('egg').Controller;
const jwt=require('jsonwebtiken');

const createRule={
    stu:{
        type:'string'
    },
    pwd:{
        type:'password',
        // compare:'re-password',
    },
}


class UserController extends Controller {
    
  async registry() {
        const {ctx}=this;

        let {name,pwd,stu,role}=ctx.request.body;

        if(!name||!pwd||!stu||!role){
            ctx.body={
                code:2,
                mes:'缺少参数'
            }
            return;
        }
        let user=await ctx.service.user.getuser(stu);
        if(res.length>0){   
                ctx.body={
                    code:3,
                    mes:'该用户已经注册'
                }
                return;
        }
        let res=await ctx.service.user.registry({...ctx.request.body,pwd:ctx.helper.help(pwd)});
        if(res.affectedRows==1){
            ctx.body={
                code:0,
                mes:'注册成功'
            }
        }else{
            ctx.body={
                code:1,
                mes:'注册失败'
            }
        }
        ctx.body=res;
  }

  async login(){
      const {ctx}=this;
      let {name,pwd}=ctx.request.body;

      if(!name||!pwd){
          ctx.body={
              code:2,
              mes:'缺少参数'
          }
          return;
      }



      try{
        ctx.validate(createRule);
        let res=await ctx.service.user.getuser(stu);
        if(user.length==0){
          ctx.body={
              code:3,
              mes:"这个用户还没注册"
          }
          return;
      }
  
              let res=await ctx.service.user.login({...ctx.request.body,pwd:ctx.helper.help(pwd)});
              let token=jwt.sign({...res[0]},ctx.app.config.keys,{expiresIn:'10h'})
          if(res.length>0){
              ctx.body={
                  code:0,
                  uid:res[0].id,
                  rid:res[0].role,
                  token,
                  mes:'登陆成功'
              }
          }else{
              ctx.body={
                  code:1,
                  mes:'登陆失败'
              }
          }
      }catch(e){
          ctx.body={
              code:4,
              mes:'参数类校验失败'
          }
      }
     



  }

  async getmenu(){
      const {ctx}=this;
      let {rid}=ctx.query;
      if(!rid){
        ctx.body={
            code:2,
            mes:'少参数'
        }
        return;
      }

      let res=await ctx.service.scores.addscores(ctx.request.body);
    //   ctx.body=res;
    // if(res.length>=0){
    //     ctx.body={
    //         code:0,
    //         date:res
    //     }
    // }
    if(res.affectedRows==1){
        ctx.body={
            code:0,
            mes:'添加成功'
        }
    }else{
        ctx.body={
            code:1,
            mes:'添加失败'
        }
    }
  }

  async getstudent(){
      const {ctx}=this;
      let res=await ctx.service.user.getstudent();
      ctx.body=res;
  }
}

module.exports = UserController;
